/**
 * Copyright 2005 The Apache Software Foundation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.edi.client.plugin;

import java.lang.reflect.Method;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang.time.DateUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.edi.Constant;

/**
 * 插件方法，封装了脚本类中的服务方法
 * 
 * @author 红木
 * 
 */
public class PluginMethod {
	private Method m;
	private List<Class> paramTypes;
	private static Log log = LogFactory.getLog(ScriptPlugin.class);
	private Class pluginClazz;

	public PluginMethod(Method m, Class pluginClazz) {
		Class[] paramClasses = m.getParameterTypes();
		this.paramTypes = Arrays.asList(paramClasses);
		this.m = m;
		this.pluginClazz = pluginClazz;
	}

	public Object clientInvoke(List<String> paramValues) throws Exception {
		Object[] args = madeArgs(paramValues);
		return m.invoke(pluginClazz.newInstance(), args);
	}

	public Object serverInvoke(List<Object> paramValues) throws Exception {
		return m.invoke(pluginClazz.newInstance(), paramValues.toArray());
	}

	private Object[] madeArgs(List<String> paramValues) throws ParseException {
		ArrayList<Object> args = new ArrayList<Object>();
		for (int index = 0; index < paramTypes.size(); index++) {
			Class paramType = paramTypes.get(index);
			String paramValue = paramValues.get(index);
			if (paramType == String.class)
				args.add(paramValue);
			else if (paramType == int.class)
				args.add(Integer.parseInt(paramValue));
			else if (paramType == Date.class)
				args.add(DateUtils.parseDate(paramValue,
						Constant.simpleDateFormate));
			else if (paramType == float.class)
				args.add(Float.parseFloat(paramValue));
		}
		log.debug("脚本参数数量为：" + args.size());
		if (args.size() != paramValues.size()) {
			throw new ParseException("脚本服务参数转换错误，应转换数量为：" + paramValues.size()
					+ "，实际转换数量为：" + args.size(), args.size()
					- paramValues.size());
		}
		return args.toArray();
	}

}